/*
 * this script is written in windows fetch, should be used in html as following:
 * this script also depends on jweixin-1.6.0.js, so we can use wx.config
 *
        <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
        <script src="https://totemlife.cn/apps/js/wx-client-dom.js"></script>
 *
 */
document.addEventListener("DOMContentLoaded", function() {

    const title = document.title || '二代菌临床前沿';
    const descriptionElement = document.querySelector('head meta[property="og:description"]') || document.querySelector('head meta[name="description"]');
    const description = descriptionElement ? descriptionElement.getAttribute('content') : '';

    const rid = localStorage.getItem('totemUID') || 676;
    const url = location.href;
    const referUrl = encodeURIComponent(url);
    const link =  `https://totemlife.cn/apps/refer?rid=${rid}&dest=${referUrl}`;

    let imgUrl = 'https://totemlife.cn/apps/public/totemlife-0f4c81-300x300.png';

    // 获取m-hero__picture元素，如果不存在，则获取页面上的第一个img元素的父元素
    const pictureElement = document.querySelector('.m-hero__picture') || (document.querySelector('img') ? document.querySelector('img').parentNode : null);
    if (pictureElement) {
        // 如果存在img元素，则获取其src属性，否则获取video元素的poster属性
        const imgElement = pictureElement.querySelector('img');
        const videoElement = pictureElement.querySelector('video');
        imgUrl = imgElement ? imgElement.getAttribute('src') : videoElement ? videoElement.getAttribute('poster') : imgUrl;
    };
    // 检查是否有自定义的图片URL
    const customImageMeta = document.querySelector('meta[name="custom-image"]');
    if (customImageMeta) imgUrl = customImageMeta.getAttribute('content');

    window.fetch(`https://totemlife.cn/apps/get-signature2?url=${encodeURIComponent(location.href)}`).then(res => res.json()).then(data => {
        wx.config({
            debug: false,
            appId: data.appId, timestamp: data.timestamp, nonceStr: data.nonceStr, signature: data.signature,
            jsApiList: [
                'checkJsApi', 'onMenuShareWeibo', 'hideMenuItems', 'closeWindow', 'chooseImage',
                'updateAppMessageShareData', 'updateTimelineShareData', 'onMenuShareWeibo', 'onMenuShareQZone'
            ],
            openTagList: ['wx-open-launch-weapp']
        });
        wx.ready(function() {
            let sdata = { title: title, desc: description, link: link, imgUrl: imgUrl, success: function(){}, cancel: function(){} };
            wx.updateAppMessageShareData(sdata);
            wx.updateTimelineShareData({...sdata, title: title + '：' + description});
            wx.onMenuShareWeibo(sdata);
            wx.onMenuShareQZone(sdata);
            let cw = document.getElementById('closeWindow');
            if (cw) cw.addEventListener('click', (e)=>{ e.preventDefault(); wx.closeWindow(); }, false);

            wx.miniProgram.getEnv((res) => {
                if (res.miniprogram) {
                    //向小程序发出OG标签，当小程序退出或转发时会接受，注意是累计接受
                    let ogData = { title, description, imgUrl, url };
                    wx.miniProgram.postMessage({data: ogData}); //一定用data

                    // 处理PDF链接
                    const pdfLinks = document.querySelectorAll('a[href*=".cn"][href*=".pdf"]');
                    pdfLinks.forEach(link => {
                        link.addEventListener('click', function(event) {
                            event.preventDefault();
                            const pdf = encodeURIComponent(this.getAttribute('href'));
                            let linkTitle = title;
                            let linkDescription = description;
                            let linkImgUrl = encodeURIComponent('https://totemlife.cn/apps/public/pdf-viewer-cover.png');
                            // 检查是否在kg-file-card内部
                            const fileCard = this.closest('.kg-file-card');
                            if (fileCard) {
                                // 从kg-file-card卡片获取标题和描述
                                const cardTitle = fileCard.querySelector('.kg-file-card-title');
                                const cardCaption = fileCard.querySelector('.kg-file-card-caption');
                                if (cardTitle) linkTitle = encodeURIComponent(cardTitle.textContent);
                                if (cardCaption) linkDescription = encodeURIComponent(cardCaption.textContent);
                            } else {
                                // 对于普通链接，使用链接文本作为标题
                                if (this.textContent && this.textContent.trim() !== '') {
                                    linkTitle = encodeURIComponent(this.textContent.trim());
                                }
                            }
                            const baseUrl = encodeURIComponent(location.href);
                            const url = `/pages/pdf-viewer/index?url=${pdf}&title=${linkTitle}&description=${linkDescription}&baseUrl=${baseUrl}`;
                            wx.miniProgram.navigateTo({ url });
                        });
                    });

                    // 处理商品购买链接
                    const productLinks = document.querySelectorAll('a[href*="go-to-weapp"][href*="view=product"]');
                    productLinks.forEach(link => {
                        // 从URL中提取商品ID
                        const url = new URL(link.href);
                        const productId = url.searchParams.get('id');
                        // 更新链接文字
                        const spanElement = link.querySelector('span');
                        if (spanElement) {
                            spanElement.textContent = '返回商城购买';
                        }
                        // 添加点击事件处理
                        link.addEventListener('click', function(event) {
                            event.preventDefault();
                            wx.miniProgram.navigateTo({
                                url: `/pages/goods_details/index?id=${productId}`
                            });
                        });
                    });

                    //如果在小程序运行环境中，将原来网页上的URL Scheme跳转小程序替换为用JS-SDK打开
                    let contactUsLink = document.getElementById('contact-us-href');
                    if (contactUsLink) {
                        document.getElementById('contact-message').innerText="回到首页";
                        contactUsLink.addEventListener('click', function(event) {
                            event.preventDefault(); // 阻止默认的链接跳转行为
                            wx.miniProgram.switchTab({url: '/pages/index/index'});
                        });
                    }

                    document.querySelectorAll('#tmall-app-home-title').forEach(element=>{
                        element.innerHTML = ` <i class="fa fa-house"></i> 图腾生命医学 `;
                    });

                    // 处理所有 tmall-app-home-link 链接
                    const tmallHomeLinks = document.querySelectorAll('#tmall-app-home-link');
                    tmallHomeLinks.forEach(link => {
                        link.addEventListener('click', function(event) {
                            event.preventDefault(); // 阻止默认的链接跳转行为
                            wx.miniProgram.switchTab({url: '/pages/index/index'});
                        });
                    });

                } else {
                    //只有不在小程序环境中，且未使用mta apps（例如实际为ghost应用）才调用公众号授权給localStorage打totemUID
                    const currentPath = window.location.pathname;
                    if (!currentPath.includes('/apps/')){
                        loadScript('/apps/js/if-wx-then-auth.js');
                    }
                }
            })

        });
    });

    function loadScript(url) {
        var script = document.createElement('script'); // 创建一个新的script元素
        script.src = url; // 设置script元素的src属性为指定的URL
        script.defer = true; //设置延迟加载
        document.head.appendChild(script); // 将script元素添加到document.head或document.body中
    }

});
